package com.beverages.orders.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.beverages.orders.client.MerchantCommoditiesClient;
import com.beverages.orders.client.MerchantIndividualClient;
import com.beverages.orders.entity.intermediate.Commodity;
import com.beverages.orders.entity.Orders;
import com.beverages.orders.entity.intermediate.Toppings;
import com.beverages.orders.entity.dto.intermediate.CustomerDTO;
import com.beverages.orders.entity.dto.OrdersDTO;
import com.beverages.orders.service.IOrdersService;
import com.beverages.orders.mapper.OrdersMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService {

    @Autowired
    private MerchantIndividualClient merchantIndividualClient;

    @Autowired
    private MerchantCommoditiesClient merchantCommoditiesClient;

    @Autowired
    private OrdersMapper ordersMapper;

    @Override
    public OrdersDTO convertOrdersEntityToOrdersDTO(Orders orders){

        OrdersDTO dto = new OrdersDTO();
        BeanUtils.copyProperties(orders, dto);

        if (orders.getCustomerId() != null) {
            CustomerDTO customerDTO = merchantIndividualClient.getCustomerById(orders.getCustomerId()).getData();
            if (customerDTO != null) {
                dto.setCustomerName(customerDTO.getNickname());
                dto.setCustomerPhone(customerDTO.getPhone());
            }
        }

        if (orders.getMilkteaId() != null) {
            Commodity commodity = merchantCommoditiesClient.getCommodityById(orders.getMilkteaId()).getData();
            if (commodity != null) {
                dto.setMilkteaName(commodity.getMilkteaName());
            }
        }

        String sugarLevelString;
        switch (orders.getSugarLevel()) {
            case 4:
                sugarLevelString = "全糖";
                break;
            case 3:
                sugarLevelString = "四分之三糖";
                break;
            case 2:
                sugarLevelString = "半糖";
                break;
            case 1:
                sugarLevelString = "四分之一糖";
                break;
            case 0:
                sugarLevelString = "无糖";
                break;
            default:
                sugarLevelString = "未知糖度";
                break;
        }
        dto.setSugarLevel(sugarLevelString);

        String iceLevelString;
        switch (orders.getIceLevel()) {
            case 2:
                iceLevelString = "正常冰";
                break;
            case 1:
                iceLevelString = "少冰";
                break;
            case 0:
                iceLevelString = "无冰";
                break;
            default:
                iceLevelString = "未知冰度";
                break;
        }
        dto.setIceLevel(iceLevelString);

        if (orders.getToppings() != null) {
            // 使用逗号作为分隔符分割字符串
            String[] toppingsIdsArray = orders.getToppings().split(",");

            // 创建一个列表来存储小料
            List<Integer> toppingsIdsList = new ArrayList<>();

            // 遍历字符串数组，将每个字符串转换为整数并添加到列表中
            for (String topping : toppingsIdsArray) {
                int num = Integer.parseInt(topping);
                toppingsIdsList.add(num);
            }
            List<Toppings> toppings = merchantCommoditiesClient.getToppingsByIds(toppingsIdsList).getData();
            if (toppings != null) {
                List<String > toppingsNameList = new ArrayList<>();
                for (Toppings topping : toppings) {
                    String name = topping.getName();
                    toppingsNameList.add(name);
                }
                dto.setToppings(toppingsNameList);
            }
        }

        if(orders.getOrderTime() != null){
            dto.setOrderTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(orders.getOrderTime()));
        }

        String orderStatusString;
        switch (orders.getOrderStatus()) {
            case 1:
                orderStatusString = "已下单";
                break;
            case 0:
                orderStatusString = "已撤单";
                break;
            default:
                orderStatusString = "未知订单状态";
                break;
        }
        dto.setOrderStatus(orderStatusString);

        if(orders.getCompletionTime() != null){
            dto.setCompletionTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(orders.getCompletionTime()));
        }

        String completionStatusString;
        switch (orders.getCompletionStatus()) {
            case 0:
                completionStatusString = "待制作";
                break;
            case 1:
                completionStatusString = "准备制作";
                break;
            case 2:
                completionStatusString = "制作中";
                break;
            case 3:
                completionStatusString = "制作完成";
                break;
            default:
                completionStatusString = "未知制作状态";
                break;
        }
        dto.setCompletionStatus(completionStatusString);

        String placeStatusString;
        switch (orders.getPlaceStatus()) {
            case 1:
                placeStatusString = "已取";
                break;
            case 0:
                placeStatusString = "未取";
                break;
            default:
                placeStatusString = "未知取物状态";
                break;
        }
        dto.setPlaceStatus(placeStatusString);

        if (orders.getHolderIds() != null) {
            String[] holderIdsArray = orders.getHolderIds().split(",");
            List<Integer> holderIdsList = new ArrayList<>();
            for (String holderId : holderIdsArray) {
                int num = Integer.parseInt(holderId);
                holderIdsList.add(num);
            }
            dto.setHolderIds(holderIdsList);
        }

        return dto;
    }

    @Override
    public List<Integer> getFilteredOrdersByCapacity(Integer capacity) {
        // 构建查询条件
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("order_status", 1); //已下单
        queryWrapper.eq("completion_status",0);  //待制作
        queryWrapper.eq("holder_ids", "0"); //未分配置物格

        // 根据 order_time 进行排序，时间在先排在前
        queryWrapper.orderByAsc("order_time");

        // 查询所有符合条件的记录
        List<Orders> allOrders = ordersMapper.selectList(queryWrapper);

        List<Integer> resultIds = new ArrayList<>();
        int totalCount = 0;

        // 遍历所有订单，筛选出符合 capacity 限制的订单
        for (Orders order : allOrders) {
            // 处理count为1的情况
            if (order.getCount() == 1 && totalCount + 1 <= capacity) {
                resultIds.add(order.getId()); // 添加一个id
                totalCount += 1;
            }
            // 处理count为2的情况
            else if (order.getCount() == 2 && totalCount + 2 <= capacity) {
                resultIds.add(order.getId()); // 添加一个id
                resultIds.add(order.getId()); // 再添加一个id
                totalCount += 2;
            }

            // 如果 totalCount 达到 capacity，停止添加更多记录
            if (totalCount >= capacity) {
                break;
            }
        }

        return resultIds;
    }

}
